package com.moonstar.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moonstar.pojo.Result;
import com.moonstar.pojo.User;
import com.moonstar.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;

    @CrossOrigin
    @GetMapping("/login")
    public Result login(@RequestParam("username") String username, @RequestParam("password") String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return userService.login(user);
    }


    //添加用户
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        userService.save(user);
        return Result.success(null);
    }

    //删除用户
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable Long id){
        userService.removeById(id);
        return Result.success(null);
    }

    //更改用户信息
    @PostMapping("/update")
    public Result update(@RequestBody User user){
        userService.updateById(user);
        return Result.success(null);
    }
    //查询用户列表
    @GetMapping("list")
    public Result list(){
        List<User> list = userService.list();
        return Result.success(list);
    }


    @GetMapping("/getUsername/{id}")
    public String getUsername(@PathVariable Long id) {
        String s = stringRedisTemplate.opsForValue().get("" + id);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            User user = objectMapper.readValue(s, User.class);
            return user.getUsername();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
